package com.yearEndWorkload.listen;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.yearEndWorkload.pojo.entity.ServicePerformance;
import com.yearEndWorkload.pojo.entity.WorkloadLoad;
import com.yearEndWorkload.pojo.excel.importTemplate.ServicePerformanceExcel;
import com.yearEndWorkload.service.ServicePerformanceService;

import java.util.List;

public class ServicePerformanceListener implements ReadListener<ServicePerformanceExcel> {
    private static final int BATCH_COUNT = 100;
    private ServicePerformanceService servicePerformanceService;
    public ServicePerformanceListener(ServicePerformanceService servicePerformanceService) {
        this.servicePerformanceService = servicePerformanceService;
    }
    /**
     * 缓存的数据
     */
    private List<ServicePerformance> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    @Override
    public void invoke(ServicePerformanceExcel servicePerformanceExcel, AnalysisContext analysisContext) {
        ServicePerformance servicePerformance = new ServicePerformance();
        servicePerformance.setYear(servicePerformanceExcel.getYear());
        servicePerformance.setTeacherName(servicePerformanceExcel.getTeacherName());
        servicePerformance.setManagerAmounts(servicePerformanceExcel.getManagerAmounts());
        servicePerformance.setReporter(servicePerformanceExcel.getReporter());
        cachedDataList.add(servicePerformance);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private void saveData() {
        servicePerformanceService.saveOrUpdateBatch(cachedDataList);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }
}
